
package com.example.infrastructure.impl;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.concurrent.TimeUnit;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.example.infrastructure.FileService;
import com.example.infrastructure.IntentService;
import com.example.model.IntentResponseModel;
import com.volcengine.ark.runtime.model.completion.chat.ChatCompletionRequest;
import com.volcengine.ark.runtime.model.completion.chat.ChatMessage;
import com.volcengine.ark.runtime.model.completion.chat.ChatMessageRole;
import com.volcengine.ark.runtime.service.ArkService;

import okhttp3.ConnectionPool;
import okhttp3.Dispatcher;

@Component
public class ArkAIService extends IntentService {

	static String apiKey = "d8b01b64-8e9c-47c6-9109-fcec3ca31284";
	static String baseUrl = "https://ark.cn-beijing.volces.com/api/v3";
	static String model = "ep-20250408155819-pkxs9";

	static ConnectionPool connectionPool = new ConnectionPool(5, 1, TimeUnit.SECONDS);
	static Dispatcher dispatcher = new Dispatcher();
	static ArkService service = ArkService.builder().dispatcher(dispatcher).connectionPool(connectionPool)
			.baseUrl(baseUrl).apiKey(apiKey).build();

	@Autowired
	private FileService fileService;

	@Override
	public IntentResponseModel llmResolveIntent(String query) {

		String systemPromptTemplate = fileService.readFile("ai/route-system-prompt.txt");
		String routeMappingInfo = fileService.readFile("ai/route.json");
		String systemPrompt = systemPromptTemplate.replace("@@@@@@", routeMappingInfo);

		StringBuilder result = new StringBuilder();

		final List<ChatMessage> messages = new ArrayList<>();
		final ChatMessage systemMessage = ChatMessage.builder().role(ChatMessageRole.SYSTEM).content(systemPrompt)
				.build();
		final ChatMessage userMessage = ChatMessage.builder().role(ChatMessageRole.USER).content(query).build();
		messages.add(systemMessage);
		messages.add(userMessage);

		System.out.println("----提示词----" + Arrays.toString(messages.toArray()));

		ChatCompletionRequest chatCompletionRequest = ChatCompletionRequest.builder().model(model).messages(messages)
				.build();

		service.createChatCompletion(chatCompletionRequest).getChoices().forEach(choice -> {
			result.append(choice.getMessage().getContent());
		});
		service.shutdownExecutor();

		System.out.println("----回答结果-------" + result.toString());

		String url = "";

		try {
			JSONObject jsonObject = JSON.parseObject(result.toString());
			boolean hasUrl = jsonObject.containsKey("url");
			if (hasUrl) {
				url = jsonObject.getString("url");
			}
		} catch (Exception e) {
		}
		return new IntentResponseModel(query, IntentResponseModel.INTENT_OPENURL, url);
	}
}
